#!/usr/bin/env python
"""

 vim: tabstop=4

 @license    http://www.gnu.org/licenses/gpl.html GPL Version 3
 @author     Ian Moore <imooreyahoo@gmail.com>
 @copyright  Copyright (c) 2011 Ian Moore
 @version    $Id: omvmbox.py 81 2011-12-13 18:25:04Z imooreyahoo@gmail.com $

 This file is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.

 This file is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this file. If not, see <http://www.gnu.org/licenses/>.

Thanks to:

	http://onlamp.com/pub/a/python/2007/06/28/processing-mailbox-files-with-mailboxpy.html?page=3

"""

import sys, mailbox, rfc822, pprint, json, time, traceback

# Default postfix spool for root
mbox = mailbox.mbox("/var/mail/root")

class omvMbox(object):

	""" Return a list of messages """
	def getMessages(self):

		msgs = []

		for uuid, msg in mbox.iteritems():
			msgs.append({
				'uuid' : uuid,
				'subject' : msg['subject'],
				'unread' : msg.get_flags().find('R') == -1,
				'date' : int(time.mktime(rfc822.parsedate(msg.get('Date'))))
			})

		return msgs

	""" Get a single message """
	def getMessage(self, uuid):

		[uuid] = uuid
		msg = mbox.get_message(int(uuid))
		
		return {
			'uuid' : uuid,
			'subject' : msg['subject'],
			'date' : int(time.mktime(rfc822.parsedate(msg.get('Date')))),
			'contentType' : msg.get_content_type(),
			'body' : msg.get_payload(decode=True)
		}

	""" Get the number of unread messages """
	def getUnreadCount(self):

		unreadCount = 0
		for msg in mbox:
			if msg.get_flags().find('R') < 0:
				unreadCount = unreadCount + 1

		return unreadCount

	""" Delete messages and flush mbox """
	def deleteMessages(self, args):

		try:
			mbox.lock()
			for uuid in args:
				del mbox[int(uuid)]
			mbox.flush()
		finally:
			# unlocks mbox
			mbox.close()

		return {'result':1}

	""" Set message flags """
	def setFlags(self, args):

		flags = args[0]
		messages = args[1:]

		try:
			mbox.lock()
			for uuid in messages:
				msg = mbox.get_message(int(uuid))
				if flags == '-': msg.remove_flag('RODFA')
				else: msg.set_flags(flags)
				mbox[int(uuid)] = msg
			mbox.flush()
		finally:
			mbox.close()

		return {'result':1}
			
if __name__ == '__main__':

	obox = omvMbox()

	try:
	
		if len(sys.argv[2:]):
			print json.dumps(getattr(obox,sys.argv[1])(sys.argv[2:]))
		else:
			print json.dumps(getattr(obox,sys.argv[1])())

	except Exception, e:
		print json.dumps({'error':'Error: %s' % e,
			'traceback': traceback.format_exc() })

